"""验证器模块"""

import re
from typing import Optional

from .exceptions import TextTooLongException, TextTooShortException


def validate_text_length(text: str, min_length: int = 1, max_length: int = 50000) -> None:
    """验证文本长度"""
    text_length = len(text.strip())
    
    if text_length < min_length:
        raise TextTooShortException(text_length, min_length)
    
    if text_length > max_length:
        raise TextTooLongException(text_length, max_length)


def validate_text_content(text: str) -> bool:
    """验证文本内容是否有效"""
    # 去除空白字符
    clean_text = text.strip()
    
    # 检查是否为空
    if not clean_text:
        return False
    
    # 检查是否包含有效字符（非仅空白字符）
    if not re.search(r'[^\s]', clean_text):
        return False
    
    return True


def validate_email(email: str) -> bool:
    """验证邮箱格式"""
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email))


def validate_phone(phone: str) -> bool:
    """验证手机号格式"""
    pattern = r'^1[3-9]\d{9}$'
    return bool(re.match(pattern, phone))


def validate_task_id(task_id: str) -> bool:
    """验证任务ID格式"""
    # 任务ID应该是UUID格式或者特定格式
    uuid_pattern = r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
    return bool(re.match(uuid_pattern, task_id, re.IGNORECASE))


def sanitize_text(text: str) -> str:
    """清理文本内容"""
    # 移除危险字符
    dangerous_chars = ['<', '>', '"', "'", '&', '\x00']
    clean_text = text
    
    for char in dangerous_chars:
        clean_text = clean_text.replace(char, '')
    
    # 标准化空白字符
    clean_text = re.sub(r'\s+', ' ', clean_text)
    
    return clean_text.strip()


def validate_api_key(api_key: str) -> bool:
    """验证API密钥格式"""
    if not api_key:
        return False
    
    # API密钥应该是一定长度的字符串
    if len(api_key) < 16:
        return False
    
    # 只包含字母数字和特定符号
    pattern = r'^[a-zA-Z0-9\-_\.]+$'
    return bool(re.match(pattern, api_key))


def validate_url(url: str) -> bool:
    """验证URL格式"""
    url_pattern = r'^https?:\/\/(?:[-\w.])+(?::[0-9]+)?(?:\/(?:[\w\/_.])*(?:\?(?:[\w&=%.])*)?(?:#(?:[\w.])*)?)?$'
    return bool(re.match(url_pattern, url))


class TextValidator:
    """文本验证器类"""
    
    def __init__(self, min_length: int = 1, max_length: int = 50000):
        self.min_length = min_length
        self.max_length = max_length
    
    def validate(self, text: str) -> tuple[bool, Optional[str]]:
        """验证文本并返回验证结果和错误信息"""
        try:
            # 验证文本长度
            validate_text_length(text, self.min_length, self.max_length)
            
            # 验证文本内容
            if not validate_text_content(text):
                return False, "文本内容无效"
            
            return True, None
            
        except (TextTooLongException, TextTooShortException) as e:
            return False, str(e)
        except Exception as e:
            return False, f"文本验证失败: {str(e)}"
    
    def sanitize_and_validate(self, text: str) -> tuple[bool, str, Optional[str]]:
        """清理并验证文本"""
        # 先清理文本
        clean_text = sanitize_text(text)
        
        # 再验证
        is_valid, error_msg = self.validate(clean_text)
        
        return is_valid, clean_text, error_msg 